package com.common.frame.utils

import android.content.Context
import android.provider.MediaStore
import com.common.frame.bean.FileInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.util.*

object FileSelectUtil {

    var FILE_TYPE_PIC = 1
    var FILE_TYPE_VIDEO = 2
    var FILE_TYPE_AUDIO = 3
    var FILE_TYPE_DOCUMENT = 4

    suspend fun loadMusicForSDCard(context: Context) = withContext(Dispatchers.IO) {
        val musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
        val cursor = context.contentResolver.query(
            musicUri, arrayOf(
                MediaStore.Audio.Media.DATA,
                MediaStore.Audio.Media.DISPLAY_NAME,
                MediaStore.Audio.Media.DATE_ADDED,
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.DURATION,
                MediaStore.Audio.Media.SIZE
            ),
            null,
            null,
            MediaStore.Audio.Media.DATE_ADDED
        )
        val musicList: MutableList<FileInfo> = ArrayList()
        //读取扫描到的音频
        cursor?.let {
            while (it.moveToNext()) {
                //获取音频文件的ID
                val fileId = it.getInt(it.getColumnIndexOrThrow(MediaStore.Audio.Media._ID))
                // 获取音频的路径
                val path = it.getString(it.getColumnIndex(MediaStore.Audio.Media.DATA))
                //获取音频名称
                val name = it.getString(it.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME))
                //获取音频时间
                val time = it.getLong(it.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED))
                //获取音频大小
                val size = it.getLong(it.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE))
                val duration = it.getLong(it.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION))
                //过滤未下载完成或者不存在的文件
                if ("downloading" != getExtensionName(path) && "wav" == getExtensionName(path) && checkImgExists(
                        path
                    ) && size > 0
                ) {
                    musicList.add(FileInfo(fileId, name, path, size, time, duration, FILE_TYPE_AUDIO))
                }
            }
            it.close()
        }
        musicList.reverse()
        musicList
    }


    private fun checkImgExists(filePath: String): Boolean {
        return File(filePath).exists()
    }

    //Java文件操作 获取文件扩展名
    fun getExtensionName(filename: String?): String {
        if (filename != null && filename.isNotEmpty()) {
            val dot = filename.lastIndexOf('.')
            if (dot > -1 && dot < filename.length - 1) {
                return filename.substring(dot + 1)
            }
        }
        return ""
    }
}